from tqsdk import TqApi, TqAuth
import csv
from threading import Thread
import ctp.thosttraderapi as api
#THOST_FTDC_D_Buy,THOST_FTDC_D_Sell
from datetime import datetime 
from ctp.ctpApi import CTradeSpi,orderfield,FrontAddr
from info import user_info,CSVreader,fieldnames,getCode,logicalOprator,getCorrectTradePrice
class TQapi(TqApi):
    def __init__(self,info,CSVreader,tradeAPI,account= None, auth= None, url= None, backtest= None, web_gui=False, debug= None, loop= None, disable_print= False, _stock= True, _ins_url=None, _md_url=None, _td_url=None) -> None:
        super().__init__(account, auth, url, backtest, web_gui, debug, loop, disable_print, _stock, _ins_url, _md_url, _td_url)
        self.info=info
        self.CSVreader,self.tradeAPI=CSVreader,tradeAPI
        ##登陆账号
        # try:
        #     self.api = TqApi(auth=TqAuth(self.info['userinfo']['TQ_username'],self.info['userinfo']['TQ_password']))
        # except:
        #     raise Exception('登陆失败')
        self.tradespi=CTradeSpi(self.tradeAPI,orderfield)
        self.tradeAPI.RegisterSpi(self.tradespi)
        self.tradeAPI.SubscribePrivateTopic(api.THOST_TERT_QUICK)
        self.tradeAPI.SubscribePublicTopic(api.THOST_TERT_QUICK)
        self.tradeAPI.RegisterFront(FrontAddr)
        Thread(target=self.Join).start()
        self.OrderList=[]
        self.quoteDict={}
        for item in self.CSVreader:
            print(item)
            item['触发价']=float(item['触发价'])
            item['止损点数']=int(item['止损点数'])
            item['止盈点数']=int(item['止盈点数'])
            self.OrderList.append(item)
            code=getCode(item['品种'])
            exchange=self.user_info['IDtoExchange'][code]
            exchange_ID=exchange+'.'+item['品种']
            self.quoteDict[item['品种']]=self.get_quote(exchange_ID)
    def Join(self):
        self.tradeAPI.Init()
        self.tradeAPI.Join()
    def run(self):
        while 1:
            print(3)
            self.wait_update()
            print(4)
            self.checkAllOrder()
            
        self.close()
    def updateCSV(self):
        CSVwriter = csv.DictWriter(open('./OrderTable.csv','w',encoding='gbk',newline=''),fieldnames=fieldnames)
        CSVwriter.writeheader()
        CSVwriter.writerows(self.OrderList)
    def checkAllOrder(self):
        removeOrderList=[]
        for order in self.OrderList:
            # print(order['品种'])
            quote=self.quoteDict[order['品种']]
            if order['开平']=="开":
                if logicalOprator(quote.last_price,order['触发逻辑'],order['触发价']):
                    LimitPrice=getCorrectTradePrice(quote,order['多空'])
                    Direction=api.THOST_FTDC_D_Buy if order['多空']=='多' else api.THOST_FTDC_D_Sell
                    #发出开仓单，挂起平仓预埋单
                    self.tradeAPI.ReqOrderInsert(order['品种'],Direction=Direction,LimitPrice=LimitPrice,volume=order['手数'],CombOffsetFlag=api.THOST_FTDC_OF_Open)
                    print(str(datetime.utcnow()).split('.')[0],"发出开仓成交单",order)
                    removeOrderList.append(order['创建时间'])
                    if order['止盈点数']==0:return 
                    closeOrder=dict(order)
                    if order['多空']=='多':
                        closeOrder['多空']='空'
                        closeOrder['触发逻辑']=">="
                        closeOrder['触发价']=order['触发价']+quote.price_tick*order['止盈点数']
                    else:
                        closeOrder['多空']='多'
                        closeOrder['触发逻辑']="<="
                        closeOrder['触发价']=order['触发价']-quote.price_tick*order['止盈点数']
                    self.OrderList.append(closeOrder)
                    # self.OrderList.remove(order)
            else:#平仓单
                if logicalOprator(quote.last_price,order['触发逻辑'],order["触发价"]):
                    Direction=api.THOST_FTDC_D_Buy if order['多空']=='多' else api.THOST_FTDC_D_Sell
                    LimitPrice=getCorrectTradePrice(quote,order['多空'])
                    self.tradeAPI.ReqOrderInsert(order['品种'],Direction=Direction,LimitPrice=LimitPrice,volume=order['手数'],CombOffsetFlag=api.THOST_FTDC_OF_Close)
                    print(str(datetime.utcnow()).split('.')[0],"发出开仓成交单",order)
                    removeOrderList.append(order['创建时间'])
        #删去已触发预埋单
        if len(removeOrderList)==0:return
        self.OrderList=filter(lambda item:item['创建时间'] not in removeOrderList,self.OrderList)
        self.updateCSV(self.OrderList)


                
if __name__=="__main__":
    tradeAPI=api.CThostFtdcTraderApi_CreateFtdcTraderApi()
    tqAPI=TQapi(user_info,CSVreader,tradeAPI,auth=TqAuth(user_info['userinfo']['TQ_username'],user_info['userinfo']['TQ_password']))
    tqAPI.run()